/*
 * Copyright (c) 2010-2019 Nathan Rajlich
 *
 *  Permission is hereby granted, free of charge, to any person
 *  obtaining a copy of this software and associated documentation
 *  files (the "Software"), to deal in the Software without
 *  restriction, including without limitation the rights to use,
 *  copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following
 *  conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 *  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *  OTHER DEALINGS IN THE SOFTWARE.
 */
package com.game.fg.service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Collections;

public class FGWebSocket extends WebSocketServer {
    private static Logger logger = LogManager.getLogger(FGWebSocket.class.getName());
    private static FGGame game = new FGGame();
    private static int onlineNum = 0;

    public FGWebSocket(int port, Draft d) throws UnknownHostException {
        super(new InetSocketAddress(port), Collections.singletonList(d));
    }

    public FGWebSocket(InetSocketAddress address, Draft d) {
        super(address, Collections.singletonList(d));
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        logger.debug(String.format("客户端连接成功 ip:%s", conn.getRemoteSocketAddress()));
        onlineNum++;
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        logger.debug(String.format("客户端断开连接 ip:%s", conn.getRemoteSocketAddress()));
        FGUserManager.getInstance().removeUser(conn, "socket断开连接");
        onlineNum--;
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        logger.error("web socket 发生错误", ex);
    }

    @Override
    public void onStart() {
        logger.debug("服务器启动成功");
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        onMessage(conn, ByteBuffer.wrap(message.getBytes()));
    }

    @Override
    public void onMessage(WebSocket conn, ByteBuffer blob) {
        byte identity = blob.get(0);//1个字节
        byte encode = blob.get(1);//1个字节
        short length = blob.getShort(2);//2个字节
        byte version = blob.get(4);//1个字节
        byte reserve = blob.get(5);//1个字节
        short cmd = blob.getShort(6);//2个字节
        if (cmd >= 0) {
            byte[] data = new byte[length - 8];
            System.arraycopy(blob.array(), 8, data, 0, length - 8);
            //处理请求
            game.msgParse(conn, cmd, data);
        }
    }

    //发送消息到客户端使用protobuf
    static void send(WebSocket ws, int cmd, byte[] data) {
        sendMessage(ws, cmd, data, false);
    }

    //发送消息到客户端使用自定义结构
    static void sendCustom(WebSocket ws, int cmd, byte[] data) {
        sendMessage(ws, cmd, data, true);
    }

    private static void sendMessage(WebSocket ws, int cmd, byte[] data, boolean custom) {
        ByteBuffer bb = ByteBuffer.allocate(data.length + 8);
        bb.put((byte) 6);
        bb.put((byte) 0);
        bb.putShort((short) (data.length + 8));
        bb.put((byte) (custom ? 3 : 4));//0x04 ProBuffer 0x03 自定义
        bb.put((byte) 0);
        bb.putShort((short) cmd);
        bb.put(data);
        ws.send(bb.array());
    }

    //获取在线人数
    static int getOnlineNum() {
        return onlineNum;
    }

}
